import fetch from 'node-fetch'
import fs from 'fs'
import path from 'path'
import https from 'https'
import Base from '../model/base/Base.js'
import { __dirname } from '../components/Path.js'

let ymzx = __dirname + 'resource/ymzx.jpg'
const apiurllol = 'https://api.lolicon.app/setu/v2'

export class apisetu extends Base {
  constructor () {
    super({
      name: 'ad[sese]',
      dsc: '涩批',
      event: 'message',
      priority: -1,
      rule: [
        {
          reg: /^#?(来(\d+)张)?随机(loli)(api)?(图)?(.*)?$/i,
          fnc: 'loli'
        }
      ]
    })
    if (this.Config.Cfg.pixiv === null || this.Config.Cfg.pixiv === undefined) { this.Config.SetCfg('pic', 'Picture', 'true') }
  }

  async downloadImage (url, fileName, directory = '../resource') {
    const filePath = path.join(__dirname, directory, fileName)
    try {
      const response = await fetch(url, {
        agent: new https.Agent({ rejectUnauthorized: false })
      })
      const buffer = Buffer.from(await response.arraybuffer())
      fs.writeFileSync(filePath, buffer, 'binary')
      return filePath
    } catch (error) {
      logger.error(`下载图片失败: ${error.message}`)
      return null
    }
  }

  async loli (e) {
    if (!(await this.cm.checkBot(e)) || this.Config.Cfg.pixiv === false) { return false }
    await e.reply('开始了')
    let numMatch = e.msg.match(/来(\d+)张/)
    let num = numMatch ? numMatch[1] : 1
    let matched = e.msg.match(/^#?(来(\d+)张)?随机(loli)(api)?(图)?(.*)?$/i)
    let tag = matched[6] ? matched[6].replace(/ /g, '|') : ''

    const messages = ['你要的图来啦']
    let res
    let imageUrls = []
    let allImageLinks = ''
    let tosend = ''

    if (tag) {
      res = await fetch(`${apiurllol}?r18=2&num=${num}&tag=${tag}`)
    } else {
      res = await fetch(`${apiurllol}?r18=2&num=${num}`)
    }

    const result = await res.json()

    if (result.error) {
      throw new Error(`API Error: ${result.error}`)
    }

    for (const item of result.data) {
      const imageUrl = item.urls.original
      const imageInfo = `标题: ${item.title}\n作者: ${item.author}\nPID: ${item.pid}\nUID: ${item.uid}\n标签: ${item.tags.join(', ')}\n`
      imageUrls.push({ url: imageUrl, info: imageInfo })
    }

    allImageLinks = imageUrls
      .map((image) => `${image.info}\n${image.url}`)
      .join('\n\n')

    messages.push(
      ...imageUrls.map((image) => [segment.image(image.url), image.info])
    )
    const forwardMsg = e.runtime.common.makeForwardMsg(
      e,
      messages,
      '点击查看涩图'
    )

    let aw = await e.reply(forwardMsg)

    if (!aw) {
      await e.reply('消息被风控！\n' + allImageLinks)
    }
  }
}
